package com.salmon.common.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtils {

	public static List<ITree> getTreeList(List<? extends ITree> list) {
		List<ITree> parent = new ArrayList<>();
		if(list == null)
			return parent;
		Map<Object, ITree> map = new HashMap<>();
		for (ITree tree : list) {
			map.put(tree.getId(), tree);
		}

		for (ITree tree : list) {
			// 规定 parentId为 0 或者为 null 表示是根节点
			if (null != tree.getParentId() && tree.getParentId() != 0 && map.containsKey(tree.getParentId()) && map.containsKey(tree.getId())) {
				ITree temp = map.get(tree.getParentId());
				if (temp.getChildren() == null) {
					List<ITree> children = new ArrayList<>();
					children.add(tree);
					temp.setChildren(children);
				} else
					temp.getChildren().add(tree);
			} else {
				parent.add(tree);
			}
		}

		return parent;
	}

	public static ITree getTree(List<? extends ITree> list) {
		List<ITree> result = getTreeList(list);
		return result.get(0);
	}
}
